package com.sudo.boot.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    // 存放channel的容器，而且可以执行对每个channel进行操作的任务，有GlobalEventExecutor提供的单线程来执行
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 客户端上线提示
     * 将新的客户端上线信息，广播给其他所有在线客户端
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 得到当前客户端
        Channel channel = ctx.channel();
        String mes = "客户端：" + channel.remoteAddress() + "上线 \n";
        System.out.println("mes = " + mes);

        // 广播给其他客户端
        channelGroup.writeAndFlush(mes);
        channelGroup.add(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //生成一个下线的信息
        String mes = "客户端：" + channel.remoteAddress() + "下线了 \n";
        // 广播给其他客户端
        channelGroup.writeAndFlush(mes);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch->{
            if (ch != channel) {
                ch.writeAndFlush("客户端" + channel.remoteAddress() + "说：" + s +"\n");
            }else {
                ch.writeAndFlush("我说：" + s +"\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
